package org.example.Controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.*;
import java.util.*;
import java.io.IOException;

/**
 * @author rjs
 */
@RestController
@RequestMapping("/api")
public class ImageController {
    private static final String UPLOAD_DIR = System.getProperty("user.dir") + "/uploads/";

    @PostMapping("/upload")
    public ResponseEntity<List<String>> uploadImages(@RequestParam("files") MultipartFile[] files) {
        List<String> fileNames = new ArrayList<>();
        Arrays.stream(files).forEach(file -> {
            try {
                Path filePath = Paths.get(UPLOAD_DIR + file.getOriginalFilename());
                Path parentDir = filePath.getParent();
                if (!Files.exists(parentDir)) {
                    Files.createDirectories(parentDir);  // 创建所有必要的父目录
                }
                if (!Files.exists(filePath)) {
                    Files.createFile(filePath);  // 创建文件
                }
                Files.write(filePath, file.getBytes());
                fileNames.add(file.getOriginalFilename());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return new ResponseEntity<>(fileNames, HttpStatus.OK);
    }

    @GetMapping("/images/{imageName}")
    public @ResponseBody byte[] getImage(@PathVariable(value = "imageName") String imageName) throws Exception {
        Path filePath = Paths.get(UPLOAD_DIR + imageName);
        return Files.readAllBytes(filePath);
    }

    @GetMapping("/list")
    public ResponseEntity<List<String>> listImages() {
        List<String> fileNames = new ArrayList<>();
        try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(UPLOAD_DIR))) {
            for (Path path : directoryStream) {
                fileNames.add(path.getFileName().toString());
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return new ResponseEntity<>(fileNames, HttpStatus.OK);
    }
}